<template>
  <div class="orders-page">
    <h1 class="page-title">订单和配送管理</h1>
    <div class="cards-container">
      <a-card class="buyer-info-card" title="订单信息">
        <!-- <a-avatar src="https://example.com/avatar.jpg" size="64" /> -->
        <div class="buyer-details">
          <p><strong>购买人姓名:</strong> {{ orderInfo.cusName }}</p>
          <p><strong>购买人手机号码:</strong> {{ orderInfo.cusPhone }}</p>
          <p><strong>购买人地址:</strong> {{ orderInfo.cusAddress }}</p>
          <p><strong>数量:</strong> {{ orderInfo.orderBuyCount }}</p>
          <p><strong>交易金额:</strong> ¥{{ orderInfo.orderPrice }}</p>
          <p><strong>配送状态:</strong> {{ statusText }}</p>
        </div>
      </a-card>
      <a-card class="merchant-info-card" title="配送设置">
        <a-form layout="vertical">
          <a-form-item label="派送人">
            <a-input v-model:value="deliveryPerson" placeholder="请输入派送人姓名" />
          </a-form-item>
          <a-form-item label="邮费">
            <a-input v-model:value="shippingFee" 
              placeholder="请输入邮费" 
              type="number" 
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="startDelivery" :disabled="orderInfo.orderStatus !== 0">
              开始送货
            </a-button>
            <a-button danger @click="finishDelivery" :disabled="orderInfo.orderStatus !== 1">
              标记送达
            </a-button>
            <a-button danger @click="cancelOrder" :disabled="orderInfo.orderStatus !== 0">
              取消订单
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button 
              type="primary" 
              @click="saveInfo" 
              :disabled="orderInfo.orderStatus === 3 && orderInfo.orderStatus === 4">
                保存信息
            </a-button>
            <a-button danger @click="resetInfo">取消</a-button>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script>
//import { Card as ACard, Avatar as AAvatar, Form as AForm, Input as AInput, Button as AButton } from 'ant-design-vue';
import { ref, onMounted, onBeforeMount } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router';
import request from '../../../util/request';

export default {
  name: 'BusOrderManager',
  setup() {
    const route = useRoute();
    const router = useRouter();

    const orderInfo = ref({
      id: 0,
      cusId: 0,
      cusName: '',
      cusPhone: '',
      cusAddress: '',
      orderBuyCount: 0,
      orderPrice: 0,
      orderStatus: 0,
      orderPostman: '',
      orderPostage: 0,
    });

    const deliveryPerson = ref('');
    const shippingFee = ref('');
    const statusText = ref('');

    const fetchData = () => {
      const orderId = route.query.orderId;
      console.log('获取到的商品ID:', orderId);
      getOrderInfo();
    };

    const getOrderInfo = () => {
      request.post('/order/get', {
        orderid: route.query.orderId,
      }).then(res => {
        orderInfo.value.cusId = res.data.order.cusId;
        orderInfo.value.cusName = res.data.cusName;
        orderInfo.value.cusPhone = res.data.cusPhone;
        orderInfo.value.cusAddress = res.data.cusAddress;
        orderInfo.value.orderBuyCount = res.data.order.orderBuyCount;
        orderInfo.value.orderPrice = res.data.orderPrice;
        orderInfo.value.id = res.data.order.id;
        deliveryPerson.value = res.data.order.orderPostman;
        shippingFee.value = res.data.order.orderPostage;
        orderInfo.value.orderStatus = res.data.order.orderStatus;
        console.log('订单信息:', orderInfo.value);
        if (orderInfo.value.orderStatus === 0) {
          statusText.value = '待发货';
        } else if (orderInfo.value.orderStatus === 1) {
          statusText.value = '运输中';
        } else if (orderInfo.value.orderStatus === 2) {
          statusText.value = '已送达';
        } else if (orderInfo.value.orderStatus === 3) {
          statusText.value = '已签收';
        } else if (orderInfo.value.orderStatus === 4) {
          statusText.value = '申请取消';
        } else {
          statusText.value = '未知状态';
        }
      }).catch(err => {
        message.error('获取订单信息失败: ', err);
      });
    };

    const startDelivery = () => {
      if (!confirm('确定将订单标记为“正在运输”吗？')) return;
      if (!deliveryPerson.value || shippingFee.value === '' || deliveryPerson.value === '(未填写)') {
        message.error('派送人和邮费不能为空');
        return;
      }
      request.post('/order/startPost', {
        orderid: orderInfo.value.id,
      }).then(res => {
        if (res.data.flag === 'success') {
          saveInfo();
          message.success('订单状态更新为 已发货 ');
        } else {
          message.error('操作失败，请稍后重试或联系管理员');
        }
      }).catch(err => {
        message.error('操作失败: ', err);
      });
    };

    const finishDelivery = () => {
      if (!confirm('确定将订单标记为“已送达”吗？')) return;
      request.post('/order/finishPost', {
        orderid: orderInfo.value.id,
      }).then(res => {
        if (res.data.flag === 'success') {
          saveInfo();
          message.success('订单状态更新为 已送达 ');
        } else {
          message.error('操作失败，请稍后重试或联系管理员');
        }
      }).catch(err => {
        message.error('操作失败: ', err);
      });
    };

    const cancelOrder = () => {
      if (!confirm('确定取消该订单吗？取消后将不可恢复！')) return;
      request.post('/order/problem', {
        orderid: orderInfo.value.id,
        userid: orderInfo.value.cusId,
      }).then(res => {
        if (res.data.flag === 'success') {
          message.success('订单已取消');
          router.push({ name: 'BusOrders' });
        } else {
          message.error('取消失败，请稍后重试或联系管理员');
        }
      }).catch(err => {
        message.error('取消失败: ', err);
      });
    };

    const saveInfo = () => {
      request.post('/order/edit', {
        orderid: orderInfo.value.id,
        postman: deliveryPerson.value,
        postage: shippingFee.value,
        // status: orderInfo.value.orderStatus,
      }).then(res => {
        if (res.data.flag === 'success') {
          message.success('订单信息已保存');
          router.push({ name: 'BusOrders' });
        } else {
          message.error('保存失败，请稍后重试或联系管理员');
        }
      }).catch(err => {
        message.error('保存失败: ', err);
      });
    };

    const resetInfo = () => {
      deliveryPerson.value = '';
      shippingFee.value = '';
      router.push({ name: 'BusOrders' });
    };

    onBeforeMount(fetchData);

    return {
      orderInfo,
      deliveryPerson,
      shippingFee,
      statusText,
      startDelivery,
      finishDelivery,
      cancelOrder,
      saveInfo,
      resetInfo,
    };
  },
};
</script>

<style src="../../../assets/styles/busOrderManager.css" scoped></style>